package com.sicnu.cheer.leaugebar.managemodule.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.util.DateUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.wheelview.OnWheelChangedListener;
import com.sicnu.cheer.generalmodule.wheelview.WheelView;
import com.sicnu.cheer.generalmodule.wheelview.adapters.ArrayWheelAdapter;
import com.sicnu.cheer.leaugebar.managemodule.R;
import com.sicnu.cheer.leaugebar.managemodule.model.AcademyModel;
import com.sicnu.cheer.leaugebar.managemodule.model.MajorModel;
import com.sicnu.cheer.leaugebar.managemodule.service.XmlParserHandler;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by cheer on 2017/2/22.
 * 对话框的工具类
 */

public class DialogUtils implements OnWheelChangedListener {
    /**
     * 设置qq的对话框
     * @param activity
     * @param callback
     */
    public static void showSetQQDialog(final Activity activity, final DialogCallback callback) {
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_qq_set, null);
        final EditText qqET = (EditText) view.findViewById(R.id.qq_et);

        TextView textView = (TextView) view.findViewById(R.id.title);
        textView.setText("设置QQ");

        final Dialog dialog = new Dialog(activity);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        window.getAttributes().width = displayMetrics.widthPixels / 5 * 4;
        dialog.show();
        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String oldValue = qqET.getText().toString().trim();
                if (StringUtils.isEmpty(oldValue)) {
                    UIHelper.ToastMessage(activity, "QQ号码不能为空");
                }else{
                    if (callback != null) {
                        callback.confirmCallBack(oldValue);
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }
    /**
     * 选择年级对话框
     * @param context
     * @param callback
     */
    public static void showGradeChooseDialog(final Context context, final DialogCallback callback) {
        showGradeChooseDialog(context, "确定", "取消",callback);
    }

    /**
     * 选择年级对话框
     * 默认年级为当前年份，可选区域为（当前年份-5到当前年份，不考虑研究生的情况）
     * @param context
     * @param submitButton
     * @param cancelButton
     * @param callback
     */
    public static void showGradeChooseDialog(final Context context, String submitButton, String cancelButton, final DialogCallback callback) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_major_choose, null);
        ((TextView) view.findViewById(R.id.title)).setText("选择年级");

        final String[] currentGrade = new String[1];//当前年级
        final String [] grades = new String[5];
        int currentYear = DateUtil.getCurrentYear();
        for (int i=0;i<5;i++){
            grades[i]=(currentYear-i)+"级";
        }
        currentGrade[0] =grades[0];

        WheelView mViewGrade = (WheelView) view.findViewById(R.id.id_academy);
        WheelView mViewMajor = (WheelView) view.findViewById(R.id.id_major);
        mViewMajor.setVisibility(View.GONE);
        //addListener
        mViewGrade.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                currentGrade[0] =grades[newValue];
            }
        });
        mViewGrade.setViewAdapter(new ArrayWheelAdapter<>(context, grades));
        // 设置可见条目数量
        mViewGrade.setVisibleItems(7);

        //将滚动视图添加到对话框中显示
        final Dialog dialog = new Dialog(context);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new BitmapDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        window.getAttributes().width = wm.getDefaultDisplay().getWidth() / 5 * 4;
        dialog.show();

        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.confirmCallBack(currentGrade[0]);
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    private WheelView mViewAcademy;
    private WheelView mViewMajor;

    public void showMajorChooseDialog(final Context context, final DialogCallback callback) {
        showMajorChooseDialog(context, "确定", "取消",callback);
    }

    /**
     * 选择家乡对话框
     *
     * @param context
     * @param submitButton
     * @param cancelButton
     * @param callback
     */
    public void showMajorChooseDialog(final Context context, String submitButton, String cancelButton, final DialogCallback callback) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_major_choose, null);
        ((TextView) view.findViewById(R.id.title)).setText("选择专业");

        mViewAcademy = (WheelView) view.findViewById(R.id.id_academy);
        mViewMajor = (WheelView) view.findViewById(R.id.id_major);
        //addListener
        mViewAcademy.addChangingListener(this);
        mViewMajor.addChangingListener(this);
        //setUpData
        initProvinceDatas(context);
        mViewAcademy.setViewAdapter(new ArrayWheelAdapter<>(context, mAcademyDatas));
        // 设置可见条目数量
        mViewAcademy.setVisibleItems(7);
        mViewMajor.setVisibleItems(7);
        updateCities(context);

        //将滚动视图添加到对话框中显示
        final Dialog dialog = new Dialog(context);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new BitmapDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        window.getAttributes().width = wm.getDefaultDisplay().getWidth() / 5 * 4;
        dialog.show();

        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //保存家乡到本地
                if (callback != null) {
                    callback.confirmCallBack(mCurrentAcademyName + "-" + mCurrentMajorName );
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }
    /**
     * 根据当前的省，更新市WheelView的信息
     *
     * @param context
     */
    private void updateCities(Context context) {
        int pCurrent = mViewAcademy.getCurrentItem();
        mCurrentAcademyName = mAcademyDatas[pCurrent];
        String[] cities = mMajorDatasMap.get(mCurrentAcademyName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewMajor.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewMajor.setCurrentItem(0);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewAcademy) {
            updateCities(wheel.getContext());
        } else if (wheel == mViewMajor) {
            mCurrentMajorName=mMajorDatasMap.get(mCurrentAcademyName)[newValue];
        }
    }


    /**
     * 对话框点击按钮回调接口
     */
    public interface DialogCallback {
        /**
         * 确定按钮回调方法
         */
        void confirmCallBack(String string);

        /**
         * 取消按钮的回调方法
         */
        void cancelCallBack();

    }


    /**
     * 所有学院
     */
    protected String[] mAcademyDatas;
    /**
     * key - 学院 value - 专业
     */
    protected Map<String, String[]> mMajorDatasMap = new HashMap<String, String[]>();

    /**
     * 当前学院的名称
     */
    protected String mCurrentAcademyName;
    /**
     * 当前专业的名称
     */
    protected String mCurrentMajorName;
    /**
     * 解析学院-专业的XML数据
     */

    protected void initProvinceDatas(Context context) {
        List<AcademyModel> provinceList = null;
        AssetManager asset = context.getAssets();
        try {
            InputStream input = asset.open("major_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的学院、专业
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentAcademyName = provinceList.get(0).getName();
                List<MajorModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentMajorName = cityList.get(0).getName();
                }
            }
            //*/
            mAcademyDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有学院的数据
                mAcademyDatas[i] = provinceList.get(i).getName();
                List<MajorModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历学院下面的所有专业的数据
                    cityNames[j] = cityList.get(j).getName();
                }
                // 学院-专业的数据，mMajorDatasMap
                mMajorDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }
}
